package web.User;

import pojo.News;
import service.Nservice;
import service.impl.NserviceImpl;
import util.ImgName;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;

@WebServlet("/upload.do")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Nservice service = new NserviceImpl();
    public UploadServlet(){
        super();
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        News news = new News();
        String title = request.getParameter("title");//新闻标题
        String category = request.getParameter("category");//新闻类型
        String author = request.getParameter("author");//新闻作者
        String content = request.getParameter("content");// 新闻内容
        Part img = request.getPart("img");
        news.setTitle(title);
        news.setAuthor(author);
        news.setContent(content);
        news.setCategory(category);

        if (img.getSubmittedFileName() != "") {
            // 将图片存储到工程目录下文件夹中
            // 1、获取工程目录
            File savePath = new File("D:\\eeeee\\01_46_luowei\\src\\main\\webapp\\asset\\img");
            // 2、创建一个用来装下载的图片的文件夹
            savePath.mkdirs();
            // 3、图片重命名
            String imgName = new ImgName().getName();
            System.out.println(imgName);
            // 4、设置图片的路径
            String imgUrl = savePath + "\\" + imgName;
            // 5、写到对应文件夹 --绝对路径
            img.write(imgUrl);
            news.setCover_url("img/"+imgName);
        } else {
            news.setCover_url(null);
        }

        int count = service.Newsinsert(news);
        response.sendRedirect("index.jsp");

    }
}
